﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace G.Controls
{
    [TemplateVisualState(GroupName = GroupStateName, Name = NormalState)]
    [TemplateVisualState(GroupName = GroupStateName, Name = LoadedState)]
    public class LoadingImageControl : ContentControl
    {
        const string GroupStateName = "LoadingState";
        const string NormalState = "Normal";
        const string LoadedState = "Loaded";

        public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.Register("ImageSource", typeof(ImageSource), typeof(LoadingImageControl), new PropertyMetadata(null, ImageSourcePropertyChanged));

        static void ImageSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            LoadingImageControl control = d as LoadingImageControl;
            if (control != null)
            {
                VisualStateManager.GoToState(control, NormalState, false);
                System.Windows.Media.Imaging.BitmapImage image = e.NewValue as System.Windows.Media.Imaging.BitmapImage;
                if (image != null)
                    image.ImageOpened += control.ImageOpened;
            }
        }

        public static readonly DependencyProperty StretchProperty = DependencyProperty.Register("Stretch", typeof(Stretch), typeof(LoadingImageControl), new PropertyMetadata(Stretch.Fill));

        public Stretch Stretch
        {
            get
            {
                return (Stretch)this.GetValue(StretchProperty);
            }
            set
            {
                this.SetValue(StretchProperty, value);
            }
        }



        private void ImageOpened(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, LoadedState, false);
        }

        public ImageSource ImageSource
        {
            get
            {
                return this.GetValue(ImageSourceProperty) as ImageSource;
            }
            set
            {
                this.SetValue(ImageSourceProperty, value);
            }
        }



        public LoadingImageControl()
        {
            this.DefaultStyleKey = typeof(LoadingImageControl);
        }
    }
}
